package tsinghua.smxq.weather;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLHandler extends DefaultHandler {
	private List<Weather> WeatherList;
	private boolean inforcast;
	private boolean curforcast;
	private Weather currentWeather;

	public List<Weather> getWeatherList() {
		return WeatherList;
	}

	public void setWeatherList(List<Weather> WeatherList) {
		this.WeatherList = WeatherList;
	}

	public XMLHandler() {
		WeatherList = new ArrayList<Weather>();
		inforcast = false;
		curforcast = false;
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		String tagName = localName.length() != 0 ? localName : qName;
		tagName = tagName.toLowerCase();

		if (tagName.equals("forecast_conditions")) {
			inforcast = false;
			WeatherList.add(currentWeather);
		}
		if (tagName.equals("current_conditions")) {
			curforcast = false;
			WeatherList.add(currentWeather);
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		String tagName = localName.length() != 0 ? localName : qName;
		tagName = tagName.toLowerCase();
		// 判断之后天气forecast_conditions
		if (tagName.equals("forecast_conditions")) {
			inforcast = true;
			currentWeather = new Weather();
		}
		// 判断当前天气current_conditions
		if (tagName.equals("current_conditions")) {
			curforcast = true;
			currentWeather = new Weather();
		}
		if (curforcast) {

			if (tagName.equals("condition")) {
				currentWeather.setCondition(attributes.getValue("data"));
			} else if (tagName.equals("temp_c")) {
				currentWeather.setTemp_c(attributes.getValue("data"));
			} else if (tagName.equals("temp_f")) {
				currentWeather.setTemp_f(attributes.getValue("data"));
			} else if (tagName.equals("humidity")) {
				currentWeather.setHumidity(attributes.getValue("data"));
			} else if (tagName.equals("icon")) {
				currentWeather.setImageUrl(attributes.getValue("data"));
			} else if (tagName.equals("wind_condition")) {
				currentWeather.setWind_condition(attributes.getValue("data"));
			}

		}
		if (inforcast) {

			if (tagName.equals("day_of_week")) {
				currentWeather.setDay(attributes.getValue("data"));
			} else if (tagName.equals("low")) {
				currentWeather.setLowTemp(attributes.getValue("data"));
			} else if (tagName.equals("high")) {
				currentWeather.setHighTemp(attributes.getValue("data"));
			} else if (tagName.equals("icon")) {
				currentWeather.setImageUrl(attributes.getValue("data"));
			} else if (tagName.equals("condition")) {
				currentWeather.setCondition(attributes.getValue("data"));
			}
		}

	}

}
